import * as React from 'react';
import { Select } from 'antd';
import InputNumber from './InputNumber';

export interface PriceInputValue {
  number: number;
  currency: string;
}

export interface PriceInputProp {
  digit?: number;
  min?: number;
  max?: number;
  value?: PriceInputValue;
  onChange?: (value: PriceInputValue) => void
}

class PriceInput extends React.Component<PriceInputProp, any> {
  constructor(props: PriceInputProp) {
    super(props);
    const value = this.props.value || {};
    this.state = Object.assign(value, {
      number: null,
      currency: 'rmb'
    })
  }

  componentWillReceiveProps(nextProps) {
    if ('value' in nextProps) {
      const value = nextProps.value || {};
      this.setState(value);
    }
  }

  handleNumberChange = (number: number) => {
    if (!('value' in this.props)) {
      this.setState({ number });
    }
    this.triggerChange({ number });
  }
  handleCurrencyChange = (currency) => {
    if (!('value' in this.props)) {
      this.setState({ currency });
    }
    this.triggerChange({ currency });
  }
  triggerChange = (changedValue) => {
    // Should provide an event to pass value to Form.
    const onChange = this.props.onChange;
    if (onChange) {
      const value = Object.assign({}, this.state, changedValue);
      if ((value.number != undefined) && value.currency) {
        onChange(value);
      } else {
        onChange(null);
      }
    }
  }

  render() {
    const state = this.state;
    return (
      <div>
        <InputNumber
          size={state.size}
          value={state.number}
          digit={this.props.digit}
          min={this.props.min}
          max={this.props.max}
          onChange={this.handleNumberChange}
          style={{ width: '50%', marginRight: '3%' }}
          />
        <Select
          size={state.size}
          placeholder="请选择"
          value={state.currency}
          style={{ width: '45%' }}
          onChange={this.handleCurrencyChange}
          >
          <Select.Option value="rmb">RMB</Select.Option>
          <Select.Option value="dollar">Dollar</Select.Option>
        </Select>
      </div>
    );
  }
};

export default PriceInput;